package com.wwwarehouse.contract.contract;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.contract.bean.ReleaseObjectBean;
import com.wwwarehouse.contract.bean.VerifyPublishBean;
import com.wwwarehouse.contract.common.ContractCommon;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.event.PublishEvent;
import com.wwwarehouse.contract.event.SelectEvent;
import com.wwwarehouse.contract.event.VerifyIsPublishEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/10/18.
 *         <p/>
 *         选择发布对象
 */

public class ReleaseObjectFragment extends MyBaseViewPagerFragment {

    private boolean isShow = true;
    private String mSort;
    private List<FilterBean> sortList; //排序
    private Bundle arguments;
    private String currentoBuId;
    private int currentPos;
    private int currentPosition;
    private ArrayList<String> oBuIds;
    private ArrayList<String> publishData;
    private String buName;
    private boolean select;
    private ArrayList<String> selectoBuid;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ReleaseObjectFragment) {
            mActivity.setTitle(getString(R.string.select_object));
        }
    }

    @Override
    public void requestDatas() {
        sortList = new ArrayList<>();
        sortList.add(new FilterBean(true, "更新时间由近到远")); //默认排序
        sortList.add(new FilterBean(false, "更新时间由远到近"));
        mConfirmBtn.setText("保存");
        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确认
                Map<String, Object> map = new HashMap<>();
                map.put("pbUkid", arguments.getString("pbUkid"));
                map.put("oBuIds", getSelectoBuid());
                map.put("pbObjectType", "1");
                httpPost(ContractConstant.SAVEPUBLISHOBJECT, map, 2, true, "");
            }
        });

        arguments = getArguments();
        if (arguments != null) {
            publishData = arguments.getStringArrayList("publishData");
            if (publishData != null && publishData.size() != 0) {
                mConfirmBtn.setVisibility(View.VISIBLE);
                mActivity.setTitle("选择发布对象(" + publishData.size() + ")");
            } else {
                arguments.putSerializable("publishData",publishData);
            }
            SetFragmentAndPage(Integer.parseInt(arguments.getString("total")), 7, new ReleaseObjectListFragment().getClass().getName(), arguments);
        }
        EventBus.getDefault().register(this);

    }

    public ArrayList<String> getSelectoBuid() {
        oBuIds = new ArrayList<>();
        for (int i = 0; i < getSelectTag().size(); i++) {
            oBuIds.add(getSelectTag().get(i).getBuId());
        }
        return oBuIds;
    }


    @Override
    public void cancelClick() {
        ArrayList<String> publishData = ContractCommon.getInstance().getPublishObjData();
        mCustomPager.setVisibility(View.VISIBLE);
        if (publishData != null && publishData.size() != 0) {
            mConfirmBtn.setVisibility(publishData.size() > 0 ? View.VISIBLE : View.GONE);
            if (publishData.size() > 0) {
                mActivity.setTitle("选择发布对象(" + publishData.size() + ")");
            } else {
                mActivity.setTitle("选择发布对象");
            }
        }

        mEmptyLayout.setVisibility(View.GONE);
        if (arguments != null) {
            arguments.putSerializable("publishData",publishData);
            Map<String, Object> map = new HashMap<>();
            map.put("buId", arguments.getString("buId")); //   业务单位ID(必填)
            map.put("orderSort", mSort); //  排序(DESC,ASC)
            map.put("orderType", "related_time"); //  按建立时间 related_time空为按客户名称排序
            map.put("page", "1"); //  页数(分页，必填)
            map.put("relationType", "CUSTOMER"); //  CUSTOMER客户 SUPPLIER供应商
            map.put("searchText", ""); // 搜索文字(选填，空则搜全部，模糊搜索业务单位名称)
            arguments.putString("searchText", "");
            map.put("size", "7"); // 每页数量(分页，必填)
            httpPost(ContractConstant.RELATIONBUSINESSUNITLIST, map, 0, true, "");
        }

    }


    @Override
    public void sortClick(View anchor) {
        //排序
        PopUpUtils.showBubbleDown(anchor, mActivity, sortList, new BubblePopAdapter.OnPopListClickListener() {
            @Override
            public void setOnItemClickListener(int i, View view) {
                if (i == 0) {
                    mSort = "DESC";      //时间正序
                    sortList.get(0).setSelect(true);
                    sortList.get(1).setSelect(false);

                } else if (i == 1) {
                    mSort = "ASC";        //时间倒序
                    sortList.get(0).setSelect(false);
                    sortList.get(1).setSelect(true);

                }
                //接口请求
                if (arguments != null) {
                    arguments.putString("orderSort", mSort);
                    Map<String, Object> map = new HashMap<>();
                    map.put("buId", arguments.getString("buId")); //   业务单位ID(必填)
                    map.put("orderSort", mSort); //  排序(DESC,ASC)
                    map.put("orderType", "related_time"); //  按建立时间 related_time空为按客户名称排序
                    map.put("page", "1"); //  页数(分页，必填)
                    map.put("relationType", "CUSTOMER"); //  CUSTOMER客户 SUPPLIER供应商
                    map.put("searchText", ""); // 搜索文字(选填，空则搜全部，模糊搜索业务单位名称)
                    arguments.putString("searchText", "");
                    map.put("size", "7"); // 每页数量(分页，必填)
                    httpPost(ContractConstant.RELATIONBUSINESSUNITLIST, map, 0, true, "");

                }


            }
        });
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        //搜索之前选择的状态
        selectoBuid = getSelectoBuid();
        //接口请求
        if (arguments != null) {
            arguments.putSerializable("publishData",selectoBuid);
            Map<String, Object> map = new HashMap<>();
            map.put("buId", arguments.getString("buId")); //   业务单位ID(必填)
            map.put("orderSort", mSort); //  排序(DESC,ASC)
            map.put("orderType", "related_time"); //  按建立时间 related_time空为按客户名称排序
            map.put("page", "1"); //  页数(分页，必填)
            map.put("relationType", "CUSTOMER"); //  CUSTOMER客户 SUPPLIER供应商
            map.put("searchText", text); // 搜索文字(选填，空则搜全部，模糊搜索业务单位名称)
            arguments.putString("searchText", text);
            map.put("size", "7"); // 每页数量(分页，必填)
            httpPost(ContractConstant.RELATIONBUSINESSUNITLIST, map, 0, true, "");
        }

    }

    public void onEventMainThread(Object event) {
        if (event instanceof VerifyIsPublishEvent) {
            currentPos = ((VerifyIsPublishEvent) event).getPos();
            currentPosition = ((VerifyIsPublishEvent) event).getPosition();
            currentoBuId = ((VerifyIsPublishEvent) event).getoBuId();
            select = ((VerifyIsPublishEvent) event).isSelect();
            buName = ((VerifyIsPublishEvent) event).getBuName();
            Map<String, Object> map = new HashMap<>();
            map.put("buId", arguments.getString("buId"));
            map.put("oBuId", currentoBuId);
            map.put("pbObjectType", "1");
            httpPost(ContractConstant.VERIFYISPUBLISH, map, 1, true, "");
        }

    }

    //获取选择的任务数据集合
    private ArrayList<ReleaseObjectBean.BusinessListBean> getSelectTag() {
        ArrayList<ReleaseObjectBean.BusinessListBean> selectDatas = new ArrayList<>();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i) != null) {
                ReleaseObjectListFragment currentFragment = (ReleaseObjectListFragment) fragmentList.get(i);
                if (currentFragment.mAdapter != null) {
                    ArrayList<ReleaseObjectBean.BusinessListBean> selectData = currentFragment.mAdapter.getSelectData();
                    selectDatas.addAll(selectData);
                }
            }
        }
        return selectDatas;
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {

        if (what == 0) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                ReleaseObjectBean releaseObjectBean = JSON.parseObject(commonClass.getData().toString(), ReleaseObjectBean.class);
                if (releaseObjectBean.getBusinessList().size() != 0) {
                    mCustomPager.setVisibility(View.VISIBLE);
                    mEmptyLayout.setVisibility(View.GONE);
                    if ( ContractCommon.getInstance().getPublishObjData().size()!=0){
                        mConfirmBtn.setVisibility(View.VISIBLE);
                    }
                    SetFragmentAndPage(Integer.parseInt(releaseObjectBean.getTotal()), 7, new ReleaseObjectListFragment().getClass().getName(), arguments);
                } else {
                    mConfirmBtn.setVisibility(View.GONE);
                    ShowEmptyView();
                }

            } else {
                toast(commonClass.getMsg());
            }
        } else if (what == 1) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                VerifyPublishBean.DataBean dataBean = JSON.parseObject(commonClass.getData().toString(), VerifyPublishBean.DataBean.class);
                if (dataBean != null) {
                    String num = dataBean.getNum();
                    if ("0".equals(num)) {
                        EventBus.getDefault().post(new SelectEvent(currentoBuId, currentPos, currentPosition));
                        mConfirmBtn.setVisibility(getSelectoBuid().size() > 0 ? View.VISIBLE : View.GONE);
                        if (getSelectoBuid().size() > 0) {
                            mActivity.setTitle("选择发布对象(" + getSelectoBuid().size() + ")");
                        } else {
                            mActivity.setTitle("选择发布对象");
                        }
                    } else {
                        if (select) {
                            EventBus.getDefault().post(new SelectEvent(currentoBuId, currentPos, currentPosition));
                            mConfirmBtn.setVisibility(getSelectoBuid().size() > 0 ? View.VISIBLE : View.GONE);
                            if (getSelectoBuid().size() > 0) {
                                mActivity.setTitle("选择发布对象(" + getSelectoBuid().size() + ")");
                            } else {
                                mActivity.setTitle("选择发布对象");
                            }
                        } else {
                            DialogTools.getInstance().showCustomDialogPrompt(mActivity, null, String.format("之前已发布过对“%s“的资源,确定本次发布还要增加此对象吗？", buName), false, new DialogTools.ConfirmListener() {
                                @Override
                                public void setConfirmListener(Dialog dialog, View view, String s) {
                                    dialog.dismiss();
                                    EventBus.getDefault().post(new SelectEvent(currentoBuId, currentPos, currentPosition));
                                    mConfirmBtn.setVisibility(getSelectoBuid().size() > 0 ? View.VISIBLE : View.GONE);
                                    if (getSelectoBuid().size() > 0) {
                                        mActivity.setTitle("选择发布对象(" + getSelectoBuid().size() + ")");
                                    } else {
                                        mActivity.setTitle("选择发布对象");
                                    }
                                }
                            }, "增加", "不增加");
                        }
                    }


                }


            }
        } else if (what == 2) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                List<String> dataBean = JSON.parseArray(commonClass.getData().toString(), String.class);
                if (dataBean != null) {
                    EventBus.getDefault().post(new PublishEvent((ArrayList<String>) dataBean));
                    popFragment();
                }

            }


        }


    }

    @Override
    public void onDownPull() {
        if (isShow) {
            ((BaseCardDeskActivity) mActivity).hideFilterBt();
            ((BaseCardDeskActivity) mActivity).showSearchTitle();
        } else {
            ((BaseCardDeskActivity) mActivity).hideSearchTitle();
        }
        isShow = !isShow;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((BaseCardDeskActivity) mActivity).showFilterBt();
    }
}
